﻿using System;
using System.Threading.Tasks;
using System.Web;

namespace MusicPlow
{
    public class ITunes
    {
        const string c_getStoreLink = "http://itunes.apple.com/search?term={0}&limit=1&entity=song";
        const string c_noResultLink = "http://ax.itunes.apple.com/WebObjects/MZSearch.woa/wa/search?term={0}";

        public static Task<TimedOperation<string>> GetStoreLink(string searchString)
        {
            searchString = HttpUtility.UrlEncode(searchString);
            DateTime startTime = DateTime.Now;
            return WebRequestExtensions.ExecuteJsonWebRequestTask<TimedOperation<string>>(
                string.Format(c_getStoreLink, searchString),
                itunesresult =>
                {
                    TimeSpan runTime = DateTime.Now - startTime;
                    try
                    {
                        string resFromITunes = itunesresult["results"][0]["trackViewUrl"];
                        if (resFromITunes.Contains("?"))
                        {
                            resFromITunes = string.Concat(resFromITunes, "&partnerId=30");
                        }
                        else
                        {
                            resFromITunes = string.Concat(resFromITunes, "?partnerId=30");
                        }

                        var resEncodedOnce = HttpUtility.UrlEncode(resFromITunes);
                        var resEncodedTwice = HttpUtility.UrlEncode(resEncodedOnce);

                        var result = string.Concat("http://click.linksynergy.com/fs-bin/stat?id=k7qKgwT1RQg&offerid=146261&type=3&subid=0&tmpid=1826&RD_PARM1=", 
                            resEncodedTwice);

                        return new TimedOperation<string>(result, runTime);
                    }
                    catch
                    {
                        return new TimedOperation<string>(string.Format(c_noResultLink, searchString), runTime);
                    }
                });
        }
        
        public static Task<TimedOperation<string>> GetStoreLink(string artistName, string songName)
        {
            string searchString = string.Format("{0} {1}", artistName, songName);

            return GetStoreLink(searchString);
        }
    }
}
